package com.feeyo.groundservice.checkin.viewmodel

import android.app.Application
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import com.feeyo.groundservice.base_util.SuccessCallback
import com.feeyo.groundservice.base_util.formatTimeYMD
import com.feeyo.groundservice.base_util.getStartEndTime
import com.feeyo.groundservice.base_util.getZeroTime
import com.feeyo.groundservice.base_util.toSeconds
import com.feeyo.groundservice.checkin.base.GlobalHandler
import com.feeyo.groundservice.checkin.base.MyBaseObserver
import com.feeyo.groundservice.checkin.base.MyOkhttpClient
import com.feeyo.groundservice.checkin.constant.baseUrl
import com.feeyo.groundservice.checkin.constant.checkInTask
import com.feeyo.groundservice.checkin.constant.checkInTaskTemp
import com.feeyo.groundservice.checkin.constant.checkInUser
import com.feeyo.groundservice.checkin.constant.dataInitFinishedFlag
import com.feeyo.groundservice.checkin.constant.linkUserTask
import com.feeyo.groundservice.checkin.model.CheckInAreaItemBO
import com.feeyo.groundservice.checkin.model.CheckInPerSonBO
import com.feeyo.groundservice.checkin.model.CheckInTaskBO
import com.feeyo.groundservice.checkin.model.CheckInTaskTempBO
import com.feeyo.groundservice.checkin.model.LinkUserTaskBO
import com.feeyo.groundservice.checkin.model.api.ICheckInApi
import com.feeyo.groundservice.http.utils.NetClientUtil
import com.feeyo.groundservice.http.utils.getData
import kotlinx.coroutines.launch

/**
 *作者：70893 on 2025-10-23
 *描述：
 */
internal class CheckInViewModel(private val myApp: Application) : AndroidViewModel(myApp) {

    //值机柜台
    val checkInAreaList = mutableStateOf<List<CheckInAreaItemBO>?>(null)

    /**获取值机任务配置**/
    fun getSysConfig() {
        val map = hashMapOf<String, Any>().apply {
            this["config"] = "checkin_task_config"
        }
        viewModelScope.launch {
            getData(
                requestCode = {
                    val config = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .getSysConfig(map)
                    it.emit(config)
                },
                observer = object : MyBaseObserver<List<CheckInTaskTempBO>>(silence = true) {
                    override fun onSuccess(data: List<CheckInTaskTempBO>?) {
                        super.onSuccess(data)
                        //保存值机任务配置
                        checkInTaskTemp = data?.firstOrNull()
                        checkInTaskTemp?.let {
                            val time = System.currentTimeMillis() / 1000
                            //获取值机人员列表
                            getCheckInUserList(time, object : SuccessCallback {
                                override fun success() {
                                    super.success()
                                    //获取值机任务列表
                                    getCheckInList(time, object : SuccessCallback {
                                        override fun success() {
                                            super.success()
                                            //关联人员和任务
                                            val links = arrayListOf<LinkUserTaskBO>()
                                            checkInUser?.forEach { person ->
                                                val task = checkInTask?.firstOrNull {
                                                    it.user.uid == person.uid
                                                }
                                                links.add(LinkUserTaskBO(person, task))
                                            }
                                            //绑定人员和任务，刷新UI
                                            linkUserTask.value = links
                                            //可以进行滚动设置了
                                            dataInitFinishedFlag.value = true
                                        }
                                    })
                                }
                            })

                        }
                    }
                }
            )
        }
    }

    /**获取值机列表**/
    fun getCheckInList(
        currentTime: Long,
        listener: SuccessCallback
    ) {
        val timeOffset = 4 * 60 * 60//秒,生产日偏移量
        val todayZero = currentTime.getZeroTime()//当天零点 s
        val startTime = todayZero - 24 * 3600 + timeOffset//开始时间边界
        val endTime = todayZero + 2 * 24 * 3600 + timeOffset//结束时间边界


        val map = hashMapOf<String, Any>().apply {
            this["start_time"] = startTime
            this["end_time"] = endTime
            this["task_id"] = listOf(checkInTaskTemp?.task_id ?: "")//值机模板id
            this["focus_type"] = "CheckIn"
        }

        //{"start_time":1761681600,"end_time":1761940800,"task_id":["15"],"focus_type":"CheckIn"}
        viewModelScope.launch {
            getData(
                requestCode = {
                    val checkInList = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .getCheckInList(map)
                    it.emit(checkInList)
                },
                observer = object :
                    MyBaseObserver<List<CheckInTaskBO>>("查询中...", silence = false) {
                    override fun onSuccess(data: List<CheckInTaskBO>?) {
                        super.onSuccess(data)
                        checkInTask = data
                        listener.success()
                    }
                }
            )
        }
    }

    /**新增值机**/
    fun addCheckIn(
        title: String,
        startTime: Long,
        endTime: Long,
        uid: String,
        checkInStation: String,
        listener: SuccessCallback
    ) {

        val map = hashMapOf<String, Any>().apply {
            this["title"] = checkInTaskTemp?.task_title ?: "值机任务"
            this["task_id"] = checkInTaskTemp?.task_id ?: ""
            this["ps"] = startTime
            this["pe"] = endTime
            this["uid"] = listOf(uid)
            this["focus_data"] = listOf(
                hashMapOf<String, Any>().apply {
                    this["info"] = checkInStation
                    this["type"] = "CheckIn"
                }
            )
        }

        //{"uid":["10"],"focus_data":[{"type":"CheckIn","info":"222"}],"ps":1761623639,"pe":1761627239,"task_id":"15","title":"值机任务"}
        viewModelScope.launch {
            getData(
                requestCode = {
                    val checkInList = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .addCheckIn(map)
                    it.emit(checkInList)
                },
                observer = object : MyBaseObserver<Any>(msg = "提交中...") {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }


    /**获取值机人员列表
     *
     * @param date 2025-10-22   主要是为了获取人员当班状态
     * **/
    fun getCheckInUserList(date: Long, listener: SuccessCallback) {

        val times = date.formatTimeYMD().getStartEndTime()

        val map = hashMapOf<String, Any>().apply {
            this["start_time"] = times.first()
            this["end_time"] = times.last()
        }

        //{"start_time":1761667200,"end_time":1761753599}
        viewModelScope.launch {
            getData(
                requestCode = {
                    val checkInUserList = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .getCheckInUserList(map)
                    it.emit(checkInUserList)
                },
                observer = object :
                    MyBaseObserver<List<CheckInPerSonBO>>(silence = true) {
                    override fun onSuccess(data: List<CheckInPerSonBO>?) {
                        super.onSuccess(data)
                        checkInUser = data
                        listener.success()
                    }
                }
            )
        }
    }

    /**保存值机人员**/
    fun saveCheckInUser(list: List<CheckInPerSonBO>,listener: SuccessCallback) {
        val map = hashMapOf<String, Any>().apply {
            this["user_list"] = list
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val checkInUserList = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .saveCheckInUser(map)
                    it.emit(checkInUserList)
                },
                observer = object : MyBaseObserver<Any>(msg = "保存中...") {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }

    /**修改值机人员可用状态**/
    fun updateCheckInUserStatus(
        uid: String,
        status: Int,
        listener: SuccessCallback
    ) {
        val map = hashMapOf<String, Any>().apply {
            this["uid"] = uid
            this["status"] = status
        }



        viewModelScope.launch {
            getData(
                requestCode = {
                    val checkInUserList = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .updateCheckInUserStatus(map)
                    it.emit(checkInUserList)
                },
                observer = object : MyBaseObserver<Any>(msg = "更新中...") {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }

    /**获取系统值机柜台数据**/
    fun getCheckInAreaList() {
        val map = hashMapOf<String, Any>()

        viewModelScope.launch {
            getData(
                requestCode = {
                    val checkInArea = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .getCheckInAreaList(map)
                    it.emit(checkInArea)
                },
                observer = object : MyBaseObserver<List<CheckInAreaItemBO>>(silence = true) {
                    override fun onSuccess(data: List<CheckInAreaItemBO>?) {
                        super.onSuccess(data)
                        checkInAreaList.value = data
                    }
                }
            )
        }
    }


    /**删除任务**/
    fun delTask(taskId: String, listener: SuccessCallback) {

        val map = hashMapOf<String, Any>().apply {
            this["id"] = taskId
            this["remark"] = "删除任务"
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val delTask = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .delTask(map)
                    it.emit(delTask)
                },
                observer = object : MyBaseObserver<Any>(msg = "删除中...") {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }

    /**节点更新
     * @param nodeId 节点id
     * @param updateTime 当前节点服务器更新时间，后端校验使用
     * @param listener 回调
     *
     * **/
    fun updateNode(
        nodeId: String,
        updateTime: Long,//当前节点服务器更新时间，后端校验使用
        listener: SuccessCallback
    ) {
        val map = hashMapOf<String, Any>().apply {
            this["id"] = nodeId
            this["ntime"] = System.currentTimeMillis().toSeconds()
            this["updated_time"] = updateTime
            this["method"] = "normal"
        }

        viewModelScope.launch {
            getData(
                requestCode = {
                    val updateNode = getClient().getRetrofit(baseUrl)
                        .create(ICheckInApi::class.java)
                        .updateNode(map)
                    it.emit(updateNode)
                },
                observer = object :
                    MyBaseObserver<Any>(msg = "更新中...") {
                    override fun onSuccess(data: Any?) {
                        super.onSuccess(data)
                        listener.success()
                    }
                }
            )
        }
    }


    private fun getClient(): NetClientUtil = NetClientUtil.init(myApp)
        .setBaseBean(GlobalHandler.baseBean)
        .setLogEnable(true)
        .setAllowDataIsNull(true)
        .setOkhttpClientBuilder(MyOkhttpClient.client)

}